package com.xy.lang.domain;

import java.io.Serializable;
import java.util.Objects;

import static com.xy.lang.domain.PageRequest.DEFAULT_PAGE_SIZE;

/**
 *
 */
public class PageQuery implements Serializable {

    private static final long serialVersionUID = -1L;

    /**
     * page index
     */
    private int offset;

    /**
     * page size
     */
    private int rows = DEFAULT_PAGE_SIZE;

    /**
     *
     */
    public PageQuery() {
        this(0, DEFAULT_PAGE_SIZE);
    }

    /**
     *
     * @param rows
     */
    public PageQuery(int rows) {
        this(0, rows);
    }

    /**
     *
     * @param offset
     * @param rows
     */
    public PageQuery(int offset, int rows) {
        checkOffset(offset);
        checkRows(rows);
        this.offset = offset;
        this.rows = rows;
    }

    /**
     *
     * @param pageRequest
     */
    public PageQuery(PageRequest pageRequest) {
        of(pageRequest);
    }

    /**
     *
     * @param offset
     * @return
     */
    public PageQuery offset(int offset) {
        checkOffset(offset);
        setOffset(offset);
        return this;
    }

    /**
     *
     * @param rows
     * @return
     */
    public PageQuery rows(int rows) {
        checkRows(rows);
        setRows(rows);
        return this;
    }

    /**
     *
     * @param pageRequest
     * @return
     */
    public PageQuery of(PageRequest pageRequest) {
        Objects.requireNonNull(pageRequest);
        int offset0 = pageRequest.getPageIndex() * pageRequest.getPageSize();
        int rows0 = pageRequest.getPageSize();
        checkOffset(offset0);
        checkRows(rows0);
        this.offset = offset0;
        this.rows = rows0;
        return this;
    }

    @Override
    public String toString() {
        return "PageQuery{" +
                "offset=" + offset +
                ", rows=" + rows +
                '}';
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        checkOffset(offset);
        this.offset = offset;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        checkRows(rows);
        this.rows = rows;
    }

    private void checkOffset(int offset) {
        if (offset < 0) {
            throw new IndexOutOfBoundsException("The offset should be than -1.");
        }
    }

    private void checkRows(int rows) {
        if (rows < 1) {
            throw new IndexOutOfBoundsException("The rows should be than 0.");
        }
    }


    /// tests

    public static void main(String[] args) {
        PageRequest pageRequest = new PageRequest(1, 50);
        System.out.println(pageRequest);
        System.out.println(new PageQuery(pageRequest));
    }

}
